package com.leil.nio.channel;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FileChannelCopyDemo {

    public static void main(String[] args) {
        try {
            FileInputStream inputStream = new FileInputStream("d:/file-channel.txt");
            FileChannel inputChannel = inputStream.getChannel();

            FileOutputStream outputStream = new FileOutputStream("d:/file-channel-copy.txt");
            FileChannel outputChannel = outputStream.getChannel();

            ByteBuffer buffer = ByteBuffer.allocate(1024);

            while (true) {
                buffer.clear();
                int read = inputChannel.read(buffer);
                if (read == -1) {
                    break;
                }
                buffer.flip();
                outputChannel.write(buffer);
            }

            inputStream.close();
            inputChannel.close();
            outputStream.flush();
            outputStream.close();
            outputChannel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
